package proxyTest.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;

/**
 * @Author: jia
 * @Descirption:
 * @Date: 2018/5/16 14:05
 * @Modified By:
 */


public class Client {
    private String ip;
    private int port;
    private Channel channel;
    private Bootstrap b = new Bootstrap();
    EventLoopGroup worker = new NioEventLoopGroup();

    public Client() {
    }

    public Client(String ip, int port) {
        try {
            this.ip = ip;
            this.port = port;
            b.group(worker);
            b.channel(NioSocketChannel.class);
            b.remoteAddress(new InetSocketAddress(ip, port));
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast(new StringDecoder());
                    pipeline.addLast(new StringEncoder());
                    pipeline.addLast(new ClientHandler());

                }
            });
            System.out.println("proxyTest.client====start");
        }catch (Exception e){

        }


    }

    //启动客户端并不一定要创建连接，等到需要的时候再连接
    public void connect() {

        ChannelFuture fu = null;
        try {
            fu = b.connect().sync();

            Channel channel = fu.channel();
            fu.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if(channelFuture.isSuccess()){
                        System.out.println("建立连接成功==");
                    }
                }
            });
            this.channel = channel;
            //channel.closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("创建连接失败！");
        }
    }

    public void shutdown() {
        try {
            worker.shutdownGracefully().sync();
        } catch (InterruptedException e) {

        }
    }

    public void send(Object request) {
        if (channel == null || !channel.isActive()) {
            connect();
        }
        channel.writeAndFlush(request);

    }

    public Channel getChannel() {
        return channel;
    }
}
